// socket监听接口
#include <stdio.h>
#include "control.h"
#include "pthread.h"
#include "msg_queue.h"
#include "global.h"
#include "socket.h"

int s_fd = -1;

static int tcpsocket_init(void)
{
    s_fd = socket_init();
    if (-1 == s_fd)
    {
        fprintf(stderr, "error socket init\n");
        return -1;
    }

    return s_fd;
}

static void tcpsocket_final(void)
{
    close(s_fd);
    s_fd = -1;
}

// 接受网络指令
static void *tcpsocket_get(void *arg)
{
    int c_fd;
    int bytes_read;
    char buffer[16] = {0};
    struct sockaddr_in c_addr;
    mqd_t mqd = -1;
    ctr_info_t *ctr_info = NULL;

    // 对传递过来的参数进行解析
    if (NULL != arg)
    {
        ctr_info = (ctr_info_t *)arg;
    }

    if (NULL != ctr_info)
    {
        mqd = ctr_info->mqd;
    }

    while (1)
    {
        printf("%s|%s|%d\n", __FILE__, __func__, __LINE__);
        // 4.accept
        int c_addrlen = sizeof(struct sockaddr_in);
        c_fd = accept(s_fd, (struct sockaddr *)&c_addr, &c_addrlen);
        if (c_fd == -1)
        {
            perror("accept");
        }

        // 心跳包机制
        set_keepalive(c_fd, 10, 3, 3);

        printf("get connect--ip:%s,port:%d\n", inet_ntoa(c_addr.sin_addr), ntohs(c_addr.sin_port));

        while (1)
        {
            // 从套接字中读取数据
            memset(buffer, 0, sizeof(buffer));
            bytes_read = recv(c_fd, buffer, sizeof(buffer), 0);
            if (bytes_read < 0)
            {
                perror("recv failed");
                break;
            }
            else if (bytes_read == 0)
            {
                printf("Server closed the connection\n");
                break;
            }
            else
            {
                buffer[bytes_read] = '\0'; // 确保字符串以null结尾
                printf("%s|%s|%d:0x%x,0x%x,0x%x,0x%x,0x%x,0x%x\n", __FILE__, __func__, __LINE__, buffer[0], buffer[1], buffer[2], buffer[3], buffer[4], buffer[5]);

                // 符合数据格式
                if (buffer[0] == 0xAA && buffer[1] == 0x55 && buffer[4] == 0x55 && buffer[5] == 0xAA)
                {
                    printf("%s|%s|%d\n", __FILE__, __func__, __LINE__);
                    // 发送数据给消息队列，让消息队列处理
                    msg_queue_send(mqd, buffer, bytes_read);
                }
            }
        }

        close(c_fd);
    }

    pthread_exit(NULL);
}

struct control tcpsocket_control =
    {
        .control_name = "tcpsocket",
        .init = tcpsocket_init,
        .final = tcpsocket_final,
        .get = tcpsocket_get,
        .set = NULL,
        .next = NULL};

// socket监听加入链表
struct control *add_socket_to_control(struct control *phead)
{
    return add_interface_to_control_list(phead, &tcpsocket_control);
}